package com.cloud.tsp.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cloud.api.domain.alarm.AlarmCategory;
import com.cloud.api.domain.forward.VehiclePlatform;
import com.cloud.api.domain.tsp.VehicleSale;
import com.cloud.tsp.service.IAlarmCategoryService;
import com.cloud.tsp.service.IVehicleForwardService;
import com.cloud.tsp.service.IVehiclePlatformService;
import com.cloud.tsp.service.IVehicleSaleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Component
@Order(3)
public class VehicleSaleRunner implements CommandLineRunner {

    @Resource
    private IVehicleSaleService vehicleSaleService;
    @Resource
    private IAlarmCategoryService alarmCategoryService;
    @Resource
    private IVehiclePlatformService vehiclePlatformService;
    @Resource(name = "myRedis")
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void run(String... args) throws Exception {
//        List<VehicleSale> list = vehicleSaleService.lambdaQuery().select(VehicleSale::getVin,VehicleSale::getLicenseNumber,VehicleSale::getPhoneNumber,VehicleSale::getModelType).list();
        List<AlarmCategory> alarmCategories = alarmCategoryService.list();
        List<VehiclePlatform> vehiclePlatforms = vehiclePlatformService.list(new QueryWrapper<VehiclePlatform>().lambda().eq(VehiclePlatform::getStatus, 1));
        Map<String, Map<String, String>> groupedByPlantId = vehiclePlatforms.stream()
                .collect(Collectors.groupingBy(
                        VehiclePlatform::getPlatformId,
                        Collectors.toMap(
                                VehiclePlatform::getVin,
                                VehiclePlatform::getStatus
                        )
                ));
//        redisTemplate.opsForHash().putAll("VIN-INFORMATION",list.stream().collect(Collectors.toMap(VehicleSale::getVin, Function.identity())));
        redisTemplate.opsForHash().putAll("ALARM-CATEGORY",alarmCategories.stream().collect(Collectors.toMap(AlarmCategory::getCode, Function.identity())));
        for (String platformId : groupedByPlantId.keySet()) {
            redisTemplate.opsForHash().putAll("ClientForward:" + platformId,groupedByPlantId.get(platformId));
        }
    }
}
